package nico.styTool.bottomDialog

import androidx.fragment.app.FragmentActivity
import cn.vove7.bottomdialog.BottomDialogActivity
import cn.vove7.bottomdialog.builder.buttons
import cn.vove7.bottomdialog.builder.mutableList
import cn.vove7.bottomdialog.util.ObservableList
import com.blankj.utilcode.util.FileIOUtils
import com.blankj.utilcode.util.FileUtils.createOrExistsFile
import com.blankj.utilcode.util.PathUtils
import com.blankj.utilcode.util.RegexUtils
import com.drake.net.Get
import com.drake.net.utils.scopeNetLife

class BottomHor(requireActivity: FragmentActivity) {

    init {
        if (createOrExistsFile(filePath)) {
            BottomDialogActivity.builder(requireActivity) {
                mutableList(list) { _, _, s, _ ->
                    nico.styTool.Utils.setClipboard(s)
                }
                buttons {
                    positiveButton(Whole) {
                        requireActivity.scopeNetLife {
                            Get<String>("http://juzi.nienuo.net/api/?format=js&charset=utf-8").await()
                                .also {
                                    val content = "${replaceFirst(it)}\n"
                                    FileIOUtils.writeFileFromString(filePath, content, true)
                                    list.add(0, replaceFirst(it))
                                }
                        }
                    }
                }
            }
        }
    }


    private fun replaceFirst(regex: String) =
        RegexUtils.getMatches("('.+')", regex)[0].replace("'", "")

    companion object {
        private val filePath = "${PathUtils.getExternalAppDocumentsPath()}/contentHttp.txt"
        private val list by lazy {
            ObservableList.build<String?> {
                add("点击整一个(将会刷新加记录)")
                addAll(FileIOUtils.readFile2List(filePath))
            }
        }
        private const val Whole = "整一个"
    }
}